#include "Sprite.h"

Sprite::Sprite()
{
}

Sprite::Sprite(char* name, LPD3DXSPRITE SpriteHandler, int Width, int Height, int Count, int SpritePerRow, LPDIRECT3DTEXTURE9 Image,int animationRate)
{
	this-> _name = name;
	this->_spriteHandler = SpriteHandler;
	this->_width = Width;
	this->_height = Height;
	this->_spritePerRow = SpritePerRow;
	this->_Image = Image;
	this->_index = -1;
	this->_animationRate  = animationRate;
	this->_lastTime = GetTickCount();
	this->_count = Count;

	_rec.top = 0;
	_rec.left = 0;
	_rec.right = _rec.left + _width;
	_rec.bottom = _rec.top + _height;

	_autoNext = true;
}

Sprite::~Sprite(void)
{
	//delete _name;
}

void Sprite::Next()
{
	_index= (_index + 1)%_count;

	_rec.left = (_index % _spritePerRow) * _width;
	_rec.top =  (_index / _spritePerRow) * _height;
	_rec.right = _rec.left + _width;
	_rec.bottom = _rec.top + _height;
}

void Sprite::Render(float x,float y)
{
	DWORD now = GetTickCount();
	if (_animationRate == 0) return;
	if (now - _lastTime > 1000/_animationRate && _count>1 && _autoNext)
	{
		Next();
		_lastTime = now;
	}
	D3DXVECTOR3 position((float)x,(float)y,0);
	_spriteHandler->Draw(
		_Image,
		&_rec,
		NULL,
		&position,
		D3DCOLOR_XRGB(255,255,255)
		);
}

void Sprite::RenderIndex(int index, float x, float y)
{
	_rec.left = (index % _spritePerRow) * _width;
	_rec.top =  (index / _spritePerRow) * _height;
	_rec.right = _rec.left + _width;
	_rec.bottom = _rec.top + _height;
	D3DXVECTOR3 position((float)x,(float)y,0);
	_spriteHandler->Draw(
		_Image,
		&_rec,
		NULL,
		&position,
		D3DCOLOR_XRGB(255,255,255)
		);
}

int Sprite::getAnimationRate()
{
	return _animationRate;
}

Sprite::Sprite(const Sprite& sprite)
{
	this->_name = sprite._name;
	this->_spriteHandler = sprite._spriteHandler;
	this->_width = sprite._width;
	this->_height = sprite._height;
	this->_spritePerRow = sprite._spritePerRow;
	this->_Image = sprite._Image;
	this->_index = sprite._index;
	this->_animationRate  = sprite._animationRate;
	this->_lastTime = sprite._lastTime;
	this->_count = sprite._count;
	this->_rec = sprite._rec;
}